<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ok源工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            color: #333;
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }

        header {
            background: linear-gradient(90deg, #2c3e50, #4a69bd);
            color: white;
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        h1 {
            font-size: 28px;
            margin-bottom: 10px;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);
        }

        .subtitle {
            font-size: 16px;
            opacity: 0.9;
        }

        .main-content {
            display: flex;
            flex-wrap: wrap;
            padding: 20px;
            gap: 20px;
        }

        .drop-area {
            flex: 1;
            min-width: 300px;
            background: #f8f9fa;
            border: 3px dashed #4a69bd;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            transition: all 0.3s;
            cursor: pointer;
        }

        .drop-area:hover,
        .drop-area.dragover {
            background: #e9ecef;
            border-color: #1e3799;
            transform: translateY(-5px);
        }

        .drop-icon {
            font-size: 48px;
            color: #4a69bd;
            margin-bottom: 15px;
        }

        .editor-section {
            flex: 2;
            min-width: 500px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            padding: 20px;
            display: none;
        }

        .section-title {
            font-size: 20px;
            margin-bottom: 15px;
            color: #2c3e50;
            border-bottom: 2px solid #4a69bd;
            padding-bottom: 8px;
        }

        .array-section {
            margin-top: 20px;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            overflow: hidden;
        }

        .array-header {
            background: #4a69bd;
            color: white;
            padding: 12px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .array-table {
            width: 100%;
            border-collapse: collapse;
        }

        .array-table th {
            background: #f1f2f6;
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e1e8ed;
        }

        .array-table td {
            padding: 10px 15px;
            border-bottom: 1px solid #e1e8ed;
        }

        .array-table tr:hover {
            background: #f8f9fa;
        }

        .array-actions {
            display: flex;
            gap: 5px;
        }

        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s;
            margin: 0 2px;
        }

        .btn-edit {
            background: #3498db;
            color: white;
        }

        .btn-delete {
            background: #e74c3c;
            color: white;
        }

        .btn-add {
            background: #2ecc71;
            color: white;
        }

        .btn-small {
            padding: 4px 8px;
            font-size: 12px;
        }

        .btn-save {
            background: #9b59b6;
            color: white;
            padding: 10px 20px;
            font-size: 16px;
        }

        .btn-auto {
            background: #f39c12;
            color: white;
            padding: 10px 20px;
            font-size: 16px;
        }

        .btn-close {
            background: #95a5a6;
            color: white;
            padding: 10px 20px;
            font-size: 16px;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }

        .action-buttons {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            gap: 10px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        .modal-content {
            background: white;
            border-radius: 10px;
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            background: #4a69bd;
            color: white;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-body {
            padding: 20px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #2c3e50;
        }

        input,
        select,
        textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 14px;
        }

        textarea {
            min-height: 80px;
            resize: vertical;
        }

        .actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e1e8ed;
        }

        .btn-cancel {
            background: #95a5a6;
            color: white;
        }

        .btn-update {
            background: #3498db;
            color: white;
        }

        footer {
            text-align: center;
            padding: 15px;
            background: #2c3e50;
            color: white;
            font-size: 14px;
            margin-top: 20px;
        }

        .config-section {
            margin-top: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
        }

        .config-item {
            margin-bottom: 10px;
        }

        .predefined-sites {
            margin-top: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
        }

        .checkbox-cell {
            width: 40px;
            text-align: center;
        }

        .predefined-sites-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .predefined-sites-title {
            font-size: 18px;
            font-weight: bold;
            color: #2c3e50;
        }

        .predefined-sites-note {
            font-size: 14px;
            color: #7f8c8d;
            font-style: italic;
        }

        .categories-container {
            margin-top: 10px;
        }

        .categories-input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 10px;
        }

        .categories-list {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }

        .category-tag {
            background: #e3f2fd;
            border: 1px solid #bbdefb;
            border-radius: 16px;
            padding: 4px 12px;
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
        }

        .category-remove {
            background: none;
            border: none;
            cursor: pointer;
            color: #f44336;
            font-weight: bold;
            padding: 0;
            width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .category-remove:hover {
            background: #ffebee;
        }

        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }

            .drop-area,
            .editor-section {
                min-width: 100%;
            }

            .action-buttons {
                flex-direction: column;
            }

            .form-grid {
                grid-template-columns: 1fr;
            }

            .predefined-sites-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }

            .categories-input-group {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <header>
            <h1 tag="http://ok321.top/tv">ok源工具</h1>
            <p class="subtitle">拖拽JSON文件到下方区域，编辑后保存修改 | 支持自动站点处理</p>
        </header>

        <div class="main-content">
            <div class="drop-area" id="dropArea">
                <div class="drop-icon">📁</div>
                <h3>拖拽JSON文件到此处</h3>
                <p>或点击选择文件</p>
                <input type="file" id="fileInput" accept=".json" style="display: none;">
            </div>

            <div class="editor-section" id="editorSection">
                <div class="action-buttons">
                    <button class="btn btn-close" id="closeEditor">关闭编辑器</button>
                    <button class="btn btn-auto" id="autoProcessBtn">自动处理站点</button>
                    <button class="btn btn-save" id="saveBtn">保存修改</button>
                </div>

                <h2 class="section-title">JSON内容编辑</h2>

                <div class="config-section">
                    <h3>配置选项</h3>
                    <div class="config-item">
                        <label>保存名称列表 (支持逗号、顿号、分号或换行分隔):</label>
                        <textarea id="saveNames" placeholder="输入要保留的站点名称，支持多种分隔符"></textarea>
                    </div>
                </div>

                <div class="predefined-sites" id="predefinedSitesSection">
                    <div class="predefined-sites-header">
                        <div class="predefined-sites-title">预定义站点</div>
                        <div class="predefined-sites-note">勾选需要添加的站点，自动处理时会添加到当前JSON</div>
                    </div>
                    <table class="array-table">
                        <thead>
                            <tr>
                                <th class="checkbox-cell">选择</th>
                                <th>站点名称</th>
                                <th>类型</th>
                            </tr>
                        </thead>
                        <tbody id="predefinedSitesTableBody">
                            <!-- 预定义站点内容将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>

                <div id="sitesSection" class="array-section" style="display: none;">
                    <div class="array-header">
                        <h3>影视站点 (sites)</h3>
                        <button class="btn btn-add" data-array="sites">+ 添加站点</button>
                    </div>
                    <table class="array-table">
                        <thead>
                            <tr>
                                <th>站点名称</th>
                                <th>类型</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="sitesTableBody">
                            <!-- 站点内容将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>

                <div id="rulesSection" class="array-section" style="display: none;">
                    <div class="array-header">
                        <h3>过滤规则 (rules)</h3>
                        <button class="btn btn-add" data-array="rules">+ 添加规则</button>
                    </div>
                    <table class="array-table">
                        <thead>
                            <tr>
                                <th>规则名称</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="rulesTableBody">
                            <!-- 规则内容将在这里动态生成 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <footer>
            <p>ok源自动编辑工具 &copy; 2023</p>
        </footer>
    </div>

    <!-- 编辑数组项的模态框 -->
    <div class="modal" id="arrayItemModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">编辑数组项</h3>
                <span class="close-btn" id="closeModal">&times;</span>
            </div>
            <div class="modal-body" id="modalBody">
                <!-- 表单内容将动态生成 -->
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let jsonData = {};
        let currentArrayKey = null;
        let currentArrayIndex = null;
        let currentCategories = [];
        let currentHosts = [];
        let currentRegex = [];

        // 默认保存名称列表
        const defaultSaveNames = ["一起", "厂长" , "文才", "甜圈", "瓜子"];
        const replaceRules = [
            {
            "name": "量非",
            "hosts": [
                "lz",
                "vip.lz",
                "v.cdnlz",
                "hd.lz",
                "ffzy",
                "vip.ffzy",
                "hd.ffzy"
            ],
            "regex": [
                "#EXT-X-DISCONTINUITY\r*\n*#EXTINF:6.666667,[\\s\\S]*?#EXT-X-DISCONTINUITY",
                "#EXT-X-DISCONTINUITY\r*\n*#EXTINF:6.600000,[\\s\\S]*?#EXT-X-DISCONTINUITY"
            ]
            },
            {
                name: "魔都",
                hosts: [
                    "modu"
                ],
                regex: [
                    "#EXT-X-DISCONTINUITY\n(#EXT-X-KEY:METHOD=NONE\n)*#EXTINF:(3.333),\n\\S+\\.ts\\s(?:#EXTINF:[0-9.]+,\n\\S+\\.ts\\s){1,8}(?=#EXT-X)"
                ]
            },
            {
                name: "通用m3u8去广告",
                hosts: [
                    "cdn",
                    "360",
                    "hls",
                    "dytt"
                ],
                regex: [
                    "#EXT-X-DISCONTINUITY\n(#EXT-X-KEY:METHOD=NONE\n)*(?:#EXTINF:[0-9.]+,\n\\S+\\.ts\\s){1,8}(?=#EXT-X)"
                ]
            }
        ]
        const replaceLogo = ""
        const replaceLives = [
            {
                name: "MIGU",
                type: 0,
                url: "https://gh-proxy.com/https://raw.githubusercontent.com/develop202/migu_video/refs/heads/main/interface.txt",
                playerType: 2,
                timeout: 10,
                ua: "bingcha/1.1 (mianfeifenxiang) "
            }
        ]
        const replaceDoh = null
        const replaceIjk = null
        const replaceProxy = null
        const replaceParses = null
        const replaceWallpaper = null
        
        // 预定义的站点配置
        const predefinedSites = [
            {
                key: "youzhi",
                name: "🌐┃优质┃切片",
                type: 1,
                api: "https://api.yzzy-api.com/inc/apijson.php",
                searchable: 1,
                quickSearch: 1,
                filterable: 0,
                categories: ["国产剧", "香港剧", "欧美剧", "日本剧", "大陆综艺", "日韩动漫", "国产动漫", "喜剧片", "爱情片", "科幻片", "恐怖片", "动作片"]
            },
            {
                key: "360",
                name: "🌐┃360┃切片",
                type: 1,
                api: "https://360zyzz.com/api.php/provide/vod",
                searchable: 1,
                quickSearch: 1,
                filterable: 0,
                categories: [
                    "国产剧",
                    "香港剧",
                    "韩国剧",
                    "欧美剧",
                    "台湾剧",
                    "大陆综艺",
                    "日韩综艺",
                    "国产动漫",
                    "欧美动漫",
                    "日韩动漫",
                    "喜剧片",
                    "动作片",
                    "爱情片",
                    "科幻片",
                    "恐怖片"
                ]
            },
            {
                key: "modu",
                name: "🌐┃魔都┃切片",
                type: 1,
                api: "https://www.mdzyapi.com/api.php/provide/vod",
                searchable: 1,
                quickSearch: 1,
                filterable: 0,
                categories: [
                    "国产剧",
                    "香港剧",
                    "韩国剧",
                    "欧美剧",
                    "喜剧片",
                    "爱情片",
                    "科幻片",
                    "恐怖片",
                    "短剧",
                    "日韩动漫",
                    "国产动漫",
                    "大陆综艺",
                    "日韩综艺"
                ]
            },
            {
                key: "dytt",
                name: "🌐┃电影天堂┃切片",
                type: 1,
                api: "http://caiji.dyttzyapi.com/api.php/provide/vod",
                searchable: 1,
                quickSearch: 1,
                filterable: 0,
                categories: [
                    "国产剧",
                    "香港剧",
                    "韩国剧",
                    "欧美剧",
                    "喜剧片",
                    "爱情片",
                    "科幻片",
                    "恐怖片",
                    "短剧",
                    "日韩动漫",
                    "国产动漫",
                    "大陆综艺",
                    "日韩综艺"
                ]
            }
        ];

        // DOM元素
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const editorSection = document.getElementById('editorSection');
        const saveBtn = document.getElementById('saveBtn');
        const autoProcessBtn = document.getElementById('autoProcessBtn');
        const closeEditorBtn = document.getElementById('closeEditor');
        const sitesSection = document.getElementById('sitesSection');
        const rulesSection = document.getElementById('rulesSection');
        const sitesTableBody = document.getElementById('sitesTableBody');
        const rulesTableBody = document.getElementById('rulesTableBody');
        const predefinedSitesSection = document.getElementById('predefinedSitesSection');
        const predefinedSitesTableBody = document.getElementById('predefinedSitesTableBody');
        const arrayItemModal = document.getElementById('arrayItemModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalBody = document.getElementById('modalBody');
        const closeModal = document.getElementById('closeModal');
        const saveNamesTextarea = document.getElementById('saveNames');

        // 模板定义
        const templates = {
            site: {
                key: "new_site",
                name: "新站点",
                type: 1,
                api: "",
                searchable: 1,
                quickSearch: 0,
                filterable: 0,
                categories: []
            },
            rule: {
                name: "新规则",
                hosts: [],
                regex: []
            }
        };

        // 类型映射
        const typeMap = {
            0: "XML",
            1: "JSON",
            2: "爬虫源",
            3: "自定义爬虫",
            4: "服务器爬虫"
        };

        // 初始化
        function init() {
            // 设置默认保存名称
            saveNamesTextarea.value = defaultSaveNames.join(", ");

            // 渲染预定义站点
            renderPredefinedSites();
        }

        // 事件监听器
        dropArea.addEventListener('click', () => fileInput.click());
        dropArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropArea.classList.add('dragover');
        });
        dropArea.addEventListener('dragleave', () => {
            dropArea.classList.remove('dragover');
        });
        dropArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dropArea.classList.remove('dragover');
            const file = e.dataTransfer.files[0];
            if (file && file.type === 'application/json') {
                handleFile(file);
            } else {
                alert('请上传有效的JSON文件');
            }
        });

        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                handleFile(file);
            }
        });

        saveBtn.addEventListener('click', saveJson);
        autoProcessBtn.addEventListener('click', autoProcessSites);
        closeEditorBtn.addEventListener('click', closeEditor);

        // 处理文件上传
        function handleFile(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    jsonData = JSON.parse(e.target.result);
                    renderArrays();

                    // 隐藏拖拽区域，显示编辑器
                    dropArea.style.display = 'none';
                    editorSection.style.display = 'block';
                } catch (error) {
                    alert('文件解析错误: ' + error.message);
                }
            };
            reader.readAsText(file);
        }

        // 关闭编辑器
        function closeEditor() {
            if (confirm('确定要关闭编辑器吗？未保存的更改将丢失。')) {
                editorSection.style.display = 'none';
                dropArea.style.display = 'block';
                jsonData = {};
            }
        }

        // 渲染预定义站点
        function renderPredefinedSites() {
            predefinedSitesTableBody.innerHTML = '';

            predefinedSites.forEach((site, index) => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="checkbox-cell">
                        <input type="checkbox" checked="true" class="site-checkbox" data-index="${index}">
                    </td>
                    <td>${site.name || '未命名站点'}</td>
                    <td>${typeMap[site.type] || site.type}</td>
                `;
                predefinedSitesTableBody.appendChild(row);
            });
        }

        // 渲染数组表格
        function renderArrays() {
            // 渲染sites
            if (jsonData.sites && jsonData.sites.length > 0) {
                sitesSection.style.display = 'block';
                sitesTableBody.innerHTML = '';

                jsonData.sites.forEach((site, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${site.name || '未命名站点'}</td>
                        <td>${typeMap[site.type] || site.type}</td>
                        <td>
                            <div class="array-actions">
                                <button class="btn btn-edit" data-array="sites" data-index="${index}">编辑</button>
                                <button class="btn btn-delete" data-array="sites" data-index="${index}">删除</button>
                            </div>
                        </td>
                    `;
                    sitesTableBody.appendChild(row);
                });
            } else {
                sitesSection.style.display = 'none';
            }

            // 渲染rules
            if (jsonData.rules && jsonData.rules.length > 0) {
                rulesSection.style.display = 'block';
                rulesTableBody.innerHTML = '';

                jsonData.rules.forEach((rule, index) => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${rule.name || '未命名规则'}</td>
                        <td>
                            <div class="array-actions">
                                <button class="btn btn-edit" data-array="rules" data-index="${index}">编辑</button>
                                <button class="btn btn-delete" data-array="rules" data-index="${index}">删除</button>
                            </div>
                        </td>
                    `;
                    rulesTableBody.appendChild(row);
                });
            } else {
                rulesSection.style.display = 'none';
            }

            // 添加数组项操作事件
            document.querySelectorAll('.btn-edit[data-array]').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const arrayKey = e.target.getAttribute('data-array');
                    const index = parseInt(e.target.getAttribute('data-index'));
                    showArrayItemForm(arrayKey, index);
                });
            });

            document.querySelectorAll('.btn-delete[data-array]').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const arrayKey = e.target.getAttribute('data-array');
                    const index = parseInt(e.target.getAttribute('data-index'));
                    if (confirm(`确定要删除此项吗？`)) {
                        jsonData[arrayKey].splice(index, 1);
                        renderArrays();
                    }
                });
            });

            document.querySelectorAll('.btn-add[data-array]').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const arrayKey = e.target.getAttribute('data-array');
                    showArrayItemForm(arrayKey, -1);
                });
            });
        }

        // 显示数组项编辑表单
        function showArrayItemForm(arrayKey, index) {
            currentArrayKey = arrayKey;
            currentArrayIndex = index;

            const array = jsonData[arrayKey];
            const item = index >= 0 ? array[index] : {};

            // 初始化数组
            currentCategories = item.categories ? [...item.categories] : [];
            currentHosts = item.hosts ? [...item.hosts] : [];
            currentRegex = item.regex ? [...item.regex] : [];

            modalTitle.textContent = index >= 0 ?
                `编辑 ${arrayKey === 'sites' ? '站点' : '规则'}` :
                `添加 ${arrayKey === 'sites' ? '站点' : '规则'}`;

            // 获取所有可能的字段
            const allFields = new Set();
            if (array && array.length > 0) {
                array.forEach(item => {
                    Object.keys(item).forEach(key => allFields.add(key));
                });
            }

            // 如果是新项，使用模板字段
            if (index < 0) {
                const template = templates[arrayKey];
                if (template) {
                    Object.keys(template).forEach(key => allFields.add(key));
                }
            }

            // 确保sites包含categories字段
            if (arrayKey === 'sites' && !allFields.has('categories')) {
                allFields.add('categories');
            }

            let formHTML = `<div class="form-grid">`;

            allFields.forEach(field => {
                let value = item[field] || '';
                if (typeof value === 'object' && field !== 'categories' && field !== 'hosts' && field !== 'regex') {
                    value = JSON.stringify(value, null, 2);
                }

                formHTML += `
                    <div class="form-group">
                        <label for="field-${field}">${field}:</label>
                `;

                if (field === 'type') {
                    formHTML += `
                        <select id="field-${field}">
                            <option value="0" ${value === 0 || value === '0' ? 'selected' : ''}>0-XML</option>
                            <option value="1" ${value === 1 || value === '1' ? 'selected' : ''}>1-JSON</option>
                            <option value="2" ${value === 2 || value === '2' ? 'selected' : ''}>2-爬虫源</option>
                            <option value="3" ${value === 3 || value === '3' ? 'selected' : ''}>3-自定义爬虫</option>
                            <option value="4" ${value === 4 || value === '4' ? 'selected' : ''}>4-服务器爬虫</option>
                        </select>
                    `;
                } else if (field === 'searchable' || field === 'quickSearch' || field === 'filterable') {
                    formHTML += `
                        <select id="field-${field}">
                            <option value="0" ${value === 0 || value === '0' ? 'selected' : ''}>0</option>
                            <option value="1" ${value === 1 || value === '1' ? 'selected' : ''}>1</option>
                        </select>
                    `;
                } else if (field === 'categories') {
                    // 特殊处理分类字段
                    formHTML += `
                        <div class="categories-container">
                            <div class="categories-input-group">
                                <input type="text" id="category-input" placeholder="输入分类名称">
                                <button type="button" class="btn btn-add btn-small" id="add-category">添加</button>
                            </div>
                            <div class="categories-list" id="categories-list">
                                <!-- 分类标签将在这里动态生成 -->
                            </div>
                        </div>
                    `;
                } else if (field === 'hosts' || field === 'regex') {
                    // 优化数组字段，使用类似categories的添加删除方式
                    formHTML += `
                        <div class="categories-container">
                            <div class="categories-input-group">
                                <input type="text" id="${field}-input" placeholder="输入${field}值">
                                <button type="button" class="btn btn-add btn-small" id="add-${field}">添加</button>
                            </div>
                            <div class="categories-list" id="${field}-list">
                                <!-- ${field}标签将在这里动态生成 -->
                            </div>
                        </div>
                    `;
                } else if (typeof value === 'string' && value.length > 50) {
                    formHTML += `<textarea id="field-${field}" placeholder="${field}">${value}</textarea>`;
                } else {
                    formHTML += `<input type="text" id="field-${field}" value="${value}" placeholder="${field}">`;
                }

                formHTML += `</div>`;
            });

            formHTML += `</div>`;

            formHTML += `
                <div class="actions">
                    <button class="btn btn-cancel" id="cancelArrayEdit">取消</button>
                    <button class="btn btn-update" id="updateArrayItem">保存</button>
                </div>
            `;

            modalBody.innerHTML = formHTML;
            arrayItemModal.style.display = 'flex';

            // 渲染所有标签
            renderCategories();
            renderArrayTags('hosts', currentHosts);
            renderArrayTags('regex', currentRegex);

            // 添加分类相关事件监听
            document.getElementById('add-category')?.addEventListener('click', addCategory);
            document.getElementById('category-input')?.addEventListener('keypress', function (e) {
                if (e.key === 'Enter') {
                    addCategory();
                }
            });

            // 添加hosts和regex事件监听
            document.getElementById('add-hosts')?.addEventListener('click', function () {
                addArrayItem('hosts', currentHosts);
            });

            document.getElementById('add-regex')?.addEventListener('click', function () {
                addArrayItem('regex', currentRegex);
            });

            document.getElementById('hosts-input')?.addEventListener('keypress', function (e) {
                if (e.key === 'Enter') {
                    addArrayItem('hosts', currentHosts);
                }
            });

            document.getElementById('regex-input')?.addEventListener('keypress', function (e) {
                if (e.key === 'Enter') {
                    addArrayItem('regex', currentRegex);
                }
            });

            // 修复取消按钮事件监听
            document.getElementById('cancelArrayEdit').addEventListener('click', function () {
                arrayItemModal.style.display = 'none';
            });

            document.getElementById('closeModal').addEventListener('click', function () {
                arrayItemModal.style.display = 'none';
            });

            document.getElementById('updateArrayItem').addEventListener('click', updateArrayItem);
        }

        // 渲染分类标签
        function renderCategories() {
            const categoriesList = document.getElementById('categories-list');
            if (!categoriesList) return;

            categoriesList.innerHTML = '';

            currentCategories.forEach((category, index) => {
                const tag = document.createElement('div');
                tag.className = 'category-tag';
                tag.innerHTML = `
                    ${category}
                    <button type="button" class="category-remove" data-index="${index}">&times;</button>
                `;
                categoriesList.appendChild(tag);
            });

            // 添加删除分类事件
            document.querySelectorAll('.category-remove').forEach(btn => {
                btn.addEventListener('click', function () {
                    const index = parseInt(this.getAttribute('data-index'));
                    currentCategories.splice(index, 1);
                    renderCategories();
                });
            });
        }

        // 渲染数组标签（用于hosts和regex）
        function renderArrayTags(field, array) {
            const list = document.getElementById(`${field}-list`);
            if (!list) return;

            list.innerHTML = '';

            array.forEach((item, index) => {
                const tag = document.createElement('div');
                tag.className = 'category-tag';
                tag.innerHTML = `
                    ${item}
                    <button type="button" class="category-remove" data-field="${field}" data-index="${index}">&times;</button>
                `;
                list.appendChild(tag);
            });

            // 添加删除事件
            document.querySelectorAll(`.category-remove[data-field="${field}"]`).forEach(btn => {
                btn.addEventListener('click', function () {
                    const index = parseInt(this.getAttribute('data-index'));
                    array.splice(index, 1);
                    renderArrayTags(field, array);
                });
            });
        }

        // 添加分类
        function addCategory() {
            const input = document.getElementById('category-input');
            if (!input) return;

            const categoryText = input.value.trim();

            if (categoryText) {
                // 支持逗号、顿号、分号分隔多个分类
                const categoriesToAdd = categoryText.split(/[,，;；]/).map(cat => cat.trim()).filter(cat => cat !== '');

                categoriesToAdd.forEach(category => {
                    if (!currentCategories.includes(category)) {
                        currentCategories.push(category);
                    }
                });

                input.value = '';
                renderCategories();
            }
        }

        // 添加数组项（用于hosts和regex）
        function addArrayItem(field, array) {
            const input = document.getElementById(`${field}-input`);
            if (!input) return;

            const itemText = input.value.trim();

            if (itemText) {
                // 支持分隔符分隔多个值
                const itemsToAdd = itemText.split(/[,，;；]/).map(item => item.trim()).filter(item => item !== '');

                itemsToAdd.forEach(item => {
                    if (!array.includes(item)) {
                        array.push(item);
                    }
                });

                input.value = '';
                renderArrayTags(field, array);
            }
        }

        // 更新数组项
        function updateArrayItem() {
            const array = jsonData[currentArrayKey];
            const newItem = {};

            // 收集表单数据
            document.querySelectorAll('#modalBody input, #modalBody select, #modalBody textarea').forEach(input => {
                const id = input.id;
                if (id.startsWith('field-')) {
                    const field = id.substring(6);
                    let value = input.value.trim();

                    // 跳过特殊处理的字段
                    if (field === 'categories' || field === 'hosts' || field === 'regex') return;

                    // 处理数组字段
                    if (['hosts', 'regex'].includes(field)) {
                        value = value.split('\n').filter(line => line.trim() !== '');
                    }
                    // 尝试解析JSON
                    else if (value && (value.startsWith('{') || value.startsWith('['))) {
                        try {
                            value = JSON.parse(value);
                        } catch (e) {
                            // 保持为字符串
                        }
                    }

                    // 处理数字字段
                    if (['type', 'searchable', 'quickSearch', 'filterable', 'playerType'].includes(field)) {
                        value = parseInt(value) || 0;
                    }

                    // 只有非空值才添加到对象
                    if (value !== '' && value !== null && value !== undefined) {
                        newItem[field] = value;
                    }
                }
            });

            // 添加分类数据
            if (currentCategories.length > 0) {
                newItem.categories = [...currentCategories];
            }

            // 添加hosts和regex数据
            if (currentHosts.length > 0) {
                newItem.hosts = [...currentHosts];
            }
            if (currentRegex.length > 0) {
                newItem.regex = [...currentRegex];
            }

            if (currentArrayIndex >= 0) {
                // 更新现有项
                array[currentArrayIndex] = newItem;
            } else {
                // 添加新项
                if (!array) {
                    jsonData[currentArrayKey] = [];
                }
                jsonData[currentArrayKey].push(newItem);
            }

            arrayItemModal.style.display = 'none';
            renderArrays();
        }

        // 自动处理站点
        function autoProcessSites() {
            if (!jsonData.sites || jsonData.sites.length === 0) {
                alert('当前没有站点数据');
                return;
            }

            const saveNamesText = saveNamesTextarea.value.trim();
            if (!saveNamesText) {
                alert('请输入要保留的站点名称');
                return;
            }

            // 解析保存名称（支持逗号、顿号、分号或换行分隔）
            const saveNames = saveNamesText.split(/[,，;；\n]/).map(name => name.trim()).filter(name => name !== '');

            // 过滤站点(会按照保留名称排序)
            const filteredSites = saveNames.map(saveName => jsonData.sites.find(site => site.name && site.name.includes(saveName))).filter(Boolean);

            // 添加选中的预定义站点
            const selectedSites = document.querySelectorAll('.site-checkbox:checked');
            if (selectedSites.length > 0) {
                selectedSites.forEach(checkbox => {
                    const index = parseInt(checkbox.getAttribute('data-index'));
                    const site = predefinedSites[index];
                    if (!filteredSites.some(existingSite => existingSite.key === site.key)) {
                        filteredSites.push(site);
                    }
                });
            }

            // 更新数据
            jsonData.sites = filteredSites;

            jsonData = replaceParam(jsonData);
            // 重新渲染
            renderArrays();

            alert(`站点处理完成！保留 ${filteredSites.length} 个站点`);
        }

        // 清理空值
        function cleanEmptyValues(obj) {
            if (Array.isArray(obj)) {
                return obj.map(item => cleanEmptyValues(item)).filter(item =>
                    item !== null && item !== undefined && item !== '' &&
                    !(typeof item === 'object' && Object.keys(item).length === 0)
                );
            } else if (typeof obj === 'object' && obj !== null) {
                const cleaned = {};
                for (const key in obj) {
                    const value = cleanEmptyValues(obj[key]);
                    if (value !== null && value !== undefined && value !== '' &&
                        !(typeof value === 'object' && Object.keys(value).length === 0)) {
                        cleaned[key] = value;
                    }
                }
                return cleaned;
            }
            return obj;
        }

        function replaceParam(obj){
            obj.rules = replaceRules;
            obj.logo = replaceLogo
            obj.lives = replaceLives;
            obj.parses = replaceParses;
            obj.doh = replaceDoh;
            obj.ijk = replaceIjk;
            obj.proxy = replaceProxy;
            obj.wallpaper = replaceWallpaper;
            return obj;
        }

        // 保存JSON文件
        function saveJson() {
            // 清理空值
            const cleanedData = cleanEmptyValues(jsonData);

            const dataStr = JSON.stringify(cleanedData, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });

            const url = URL.createObjectURL(dataBlob);
            const a = document.createElement('a');
            a.href = url;
            let newFile = new Date(Date.now()).toLocaleDateString() + ".json";
            a.download = newFile;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            alert(`文件已保存为 ${newFile}`);
        }

        // 初始化
        init();
    </script>
</body>

</html>